package com.workshop.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.base.commom.DateUtils;
import com.base.commom.ResponseUtils;
import com.workshop.dao.AArticleDao;
import com.workshop.dao.AArticleKeyDao;
import com.workshop.dao.AUserCountDao;
import com.workshop.entity.*;
import com.workshop.service.IAArticleService;
import com.workshop.service.impl.base.BaseServiceImpl;
import com.workshop.utils.PageUtils;
import com.workshop.utils.ResultMsg;
import com.workshop.utils.check.CheckUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chengluqiang
 * @since 2019-04-13
 */
@Service
public class AArticleServiceImpl extends BaseServiceImpl<AArticleDao, AArticle> implements IAArticleService {
    @Resource
    private AArticleDao articleDao;
    @Resource
    private AArticleKeyDao articleKeyDao;
    @Resource
    private AUserCountDao aUserCountDao;

    /**
     * 所有活动列表
     * @author chenluqiang
     * @date 2019/4/13
     * @param [pageStart, pageTotal, type 0=推荐活动，1=全部活动，2=未截稿，3=已截稿]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @throws Exception 
     */
    @Override
    public Map<String, Object> allList(HttpServletRequest request,Long pageStart, Long pageTotal, Integer type) throws Exception {
        //校验参数
        if(type==null||type>3||type<0){
            return ResponseUtils.error(ResultMsg.TYPE_ERROR,"type is error!");
        }
        //初始化分页参数
        PageUtils.initialPageStart(pageStart);
        PageUtils.initialPageTotal(pageTotal);
        long sqlStart = PageUtils.countPageStart(pageStart, pageTotal);
        List<Map<String,Object>> result = null;
        if(type==0){ //推荐
        	result =  this.getCommendedArticles(request,sqlStart,pageTotal);
        }else if(type==1){ //all
            result = articleDao.allArticles(sqlStart,pageTotal);
        }else if(type==2){ //未截稿
            result = articleDao.getNotAcceptAritcles(sqlStart,pageTotal);
        }else if(type==3){ //已截稿
            result = articleDao.getStopAcceptAritcles(sqlStart,pageTotal);
        }
        //设置参数
        this.setResponseParam(result);

        return ResponseUtils.success(result);
    }

    private List<Map<String, Object>> getCommendedArticles(HttpServletRequest request, long sqlStart, Long pageTotal) throws Exception {
    	UUser user =(UUser) CheckUtil.checkOline(request);
    	List<LinkedHashMap<String,Object>> list = articleDao.getCountAndCategoryId(user.getId());
    	List<String> categorys = new ArrayList<>();
    	int i =0;
    	Long sMaxCount = null;
    	for(Map<String,Object> map : list) {
    		if(map!=null&&!map.isEmpty()) {
    			if(i==0) {
    				sMaxCount =Long.parseLong(map.get("sCount").toString());
    				String sMaxCategoryId =map.get("categoryId").toString();
    				categorys.add(sMaxCategoryId);
    			}else {
    				Long count =Long.parseLong(map.get("sCount").toString());
    				String categoryId = map.get("categoryId").toString();
    				if(count==sMaxCount) {
    					categorys.add(categoryId);
    				}
    			}
    		}
    		i++;
    	}
		return  articleDao.commendedArticles(sqlStart,pageTotal,categorys);
	}

	/**
     * 活动详情
     * @author chenluqiang
     * @date 2019/4/14
     * @param [artId]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Map<String, Object> detail(String artId,UUser user) {
        if(artId==null||StringUtils.isBlank(artId)){
            return ResponseUtils.error("参数错误");
        }
        Map<String, Object> map = articleDao.getArticleById(artId);
        if(map==null||map.isEmpty()) {
        	 return ResponseUtils.error("参数错误");
        }
        List<Map<String, Object>> categorys = articleDao.getCategorysByArtId(map.get("artId").toString());
        if(categorys==null||categorys.isEmpty()) {
        	return ResponseUtils.error("参数错误");
        }
        List<String> categorys2 = new ArrayList<>();
        for(Map<String,Object> map2 : categorys) {
    	   if(map2==null||map2.isEmpty()||map2.get("categoryId")==null||StringUtils.isBlank(map2.get("categoryId").toString())) {
    		   return ResponseUtils.error("参数错误");
           }
    	   categorys2.add(map2.get("categoryName").toString());
    	   
    	   System.out.println(user.getId());
           //保存用户浏览信息
           AUserCount aUserCount = new AUserCount();
           aUserCount.setArticleId(artId);
           aUserCount.setCategoryId(Long.valueOf(map2.get("categoryId").toString()));
           aUserCount.setUserId(user.getId());
           List<AUserCount> list = aUserCount.selectList(new EntityWrapper<>(aUserCount));
           if(list==null||list.isEmpty()) {
           	aUserCount.setCount(1);
           	aUserCount.insert();
           }else if(list.size()>1){
           	aUserCount.delete(new EntityWrapper<>(aUserCount));
           	aUserCount.setCount(1);
           	aUserCount.insert();
           }else {
           	AUserCount aUserCount2 = list.get(0);
           	aUserCount.setCount(aUserCount2.getCount()+1);
//           	aUserCount.update(new EntityWrapper<>(aUserCount));
           	aUserCountDao.update(aUserCount,new EntityWrapper<AUserCount>().eq("articleId",aUserCount.getArticleId())
           			.eq("categoryId", aUserCount.getCategoryId()).eq("userId", aUserCount.getUserId()));
           }
        }
        //设置分类参数
        this.setResponseParam(map,categorys2);
        return ResponseUtils.success(map);
    }

    @Override
    public Map<String, Object> add(String artJson) {
        if(artJson==null||StringUtils.isBlank(artJson)){
            return ResponseUtils.error("参数错误");
        }
        AArticle article = JSON.parseObject(artJson,AArticle.class);
        Map<String,Object> check = this.checkAddParam(article);
        if(check!=null){
            return check;
        }
        article.setId(UUID.randomUUID().toString().replaceAll("-",""));
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.insert();
        return ResponseUtils.success("添加成功！");
    }

    @Override
    public Map<String, Object> search(String keyword, Long pageStart, Long pageTotal) {
        //初始化分页参数
        PageUtils.initialPageStart(pageStart);
        PageUtils.initialPageTotal(pageTotal);
        long sqlStart = PageUtils.countPageStart(pageStart, pageTotal);
        List<Map<String,Object>> result = articleDao.searchList(keyword,sqlStart,pageTotal);
        //设置参数
        this.setResponseParam(result);
        return ResponseUtils.success(result);
    }

    private Map<String,Object> checkAddParam(AArticle article) {
        if(article==null){
            return ResponseUtils.error("参数错误");
        }
        if(article.getTitle()==null||StringUtils.isBlank(article.getTitle())){
            return ResponseUtils.error("会议名称不能为空！");
        }
        if(article.getStartTime()==null||StringUtils.isBlank(article.getStartTime())){
            return ResponseUtils.error("会议开始时间不能为空！");
        }
        if(article.getEndTime()==null||StringUtils.isBlank(article.getEndTime())){
            return ResponseUtils.error("会议结束时间不能为空！");
        }
        if(article.getSeat()==null||StringUtils.isBlank(article.getSeat())){
            return ResponseUtils.error("会议地址不能为空！");
        }
        if(article.getUrl()==null||StringUtils.isBlank(article.getUrl())){
            return ResponseUtils.error("会议网址不能为空！");
        }
        if(article.getContent()==null||StringUtils.isBlank(article.getContent())){
            return ResponseUtils.error("会议简介不能为空！");
        }
        return null;
    }

    /**
     * 设置返回数据
     * @author chenluqiang
     * @date 2019/4/14
     * @param [list]
     * @return void
     */
    private void setResponseParam(List<Map<String, Object>> list) {
       for(Map<String,Object> map : list){
           if(map!=null&&!map.isEmpty()){
               //截稿时间设置
               if(map.get("pressTime")!=null&& StringUtils.isNotBlank(map.get("pressTime").toString())){
                    String tempStr = "";
                   int days = DateUtils.differentDays(new Date(),DateUtils.strToSDate(map.get("pressTime").toString()));
                   if(days<0){
                       tempStr = map.get("pressTime").toString()+" (已截稿)";
                       map.put("isPress",true);
                   }else {
                       tempStr = map.get("pressTime").toString()+"(还有"+days+"天截稿)";
                   }
                   map.put("pressTime",tempStr);
               }
               //设置分类
               if(map.get("artId")!=null&& StringUtils.isNotBlank(map.get("artId").toString())){
                   List<String> categorys = articleDao.getCategorysByArtId2(map.get("artId").toString());
                   String tempStr = "";
                   for(String cag : categorys){
                       if(cag!=null){
                           tempStr += cag+",";
                       }
                   }
                   if(tempStr.length()!=0){
                       tempStr = tempStr.substring(0,tempStr.lastIndexOf(","));
                   }
                   //分类
                   map.put("categorys",tempStr);
               }
           }
       }
    }
    private void setResponseParam(Map<String,Object> map, List<String> categorys) {
            if(map!=null&&!map.isEmpty()){
                //截稿时间设置
                if(map.get("pressTime")!=null&& StringUtils.isNotBlank(map.get("pressTime").toString())){
                    String tempStr = null;
                    int days = DateUtils.differentDays(new Date(),DateUtils.strToSDate(map.get("pressTime").toString()));
                    if(days<0){
                        tempStr = map.get("pressTime").toString()+" (已截稿)";
                        map.put("isPress",true);
                    }else {
                        tempStr = map.get("pressTime").toString()+"(还有"+days+"天截稿)";
                    }
                    map.put("pressTime",tempStr);
                }
                //设置分类
                if(map.get("artId")!=null&& StringUtils.isNotBlank(map.get("artId").toString())){
                    String tempStr = "";
                    for(String cag : categorys){
                        tempStr += cag+",";
                    }
                    tempStr = tempStr.substring(0,tempStr.lastIndexOf(","));
                    //分类
                    map.put("categorys",tempStr);
                }
            }
    }

	@Override
	public Map<String, Object> noteList(Long pageStart, Long pageTotal,UUser user) {
		 //初始化分页参数
        PageUtils.initialPageStart(pageStart);
        PageUtils.initialPageTotal(pageTotal);
        long sqlStart = PageUtils.countPageStart(pageStart, pageTotal);
        List<Map<String,Object>> result = null;
        
        result = articleDao.getNoteList(sqlStart,pageTotal,user.getId());
        this.setStartTimeOutDate(result);
        return ResponseUtils.success(result);
	}

    @Override
    public Map<String, Object> adminList(Long pageStart, Long pageTotal) {
        //初始化分页参数
        PageUtils.initialPageStart(pageStart);
        PageUtils.initialPageTotal(pageTotal);
        long sqlStart = PageUtils.countPageStart(pageStart, pageTotal);
        Map<String,Object> map = new HashMap<>();
        List<Map<String,Object>> result = null;
        result = articleDao.allAdminArticles(sqlStart,pageTotal);
        //设置参数
        this.setResponseParam(result);
        long pageCount = articleDao.getArticlesCount();
        map.put("pageStart",pageStart);
        map.put("pageTotal",pageTotal);
        map.put("pageCount",pageCount);
        map.put("data",result);
        return ResponseUtils.success(map);
    }

    @Override
    public Map<String, Object> pass(String artId,Integer status) {
        if(artId==null||StringUtils.isBlank(artId)){
            return ResponseUtils.error("artId错误!");
        }
        List<String> ids = JSON.parseArray(artId,String.class);
        if(ids==null||ids.isEmpty()){
            return ResponseUtils.error("artId错误!");
        }
        if(status==null||status>2||status<0){
            return ResponseUtils.error("状态错误!");
        }
        for(String arId :ids){
            List<AArticleKey> list = articleKeyDao.selectList(new EntityWrapper<AArticleKey>(new AArticleKey().setArticleId(arId)));
            if(list==null||list.size()==0) {
                  return ResponseUtils.error("请选择该会议的分类标签!");
            }
            AArticle article = new AArticle();
            article.setId(arId);
            article.setStatus(status);
            article.updateById();
        }
        return ResponseUtils.success("审核成功！");
    }

    @Override
    public Map<String, Object> join(String artId, UUser user) {
        if(artId==null||StringUtils.isBlank(artId)){
            return ResponseUtils.error("artId错误!");
        }
        UUserArtKey uUserArtKey = new UUserArtKey();
        uUserArtKey.setArtId(artId);
        uUserArtKey.setUserId(user.getId());
        List<UUserArtKey> artKeys = uUserArtKey.selectList(new EntityWrapper(uUserArtKey));
        if(artKeys!=null&&!artKeys.isEmpty()){
            return ResponseUtils.error("您已经参加过该会议了，请到备忘录查看!");
        }
        uUserArtKey.insert();
        return ResponseUtils.success("参加会议成功，请留意备忘录会议开始时间！");
    }

    private void setStartTimeOutDate(List<Map<String, Object>> list) {
		for(Map<String,Object> map : list){
			if(map!=null&&!map.isEmpty()){
				if(map.get("startTime")!=null&&StringUtils.isNotBlank(map.get("startTime").toString())){
					int days = DateUtils.differentDays(new Date(), DateUtils.strToSDate(map.get("startTime").toString()));
					if(days<0){
						try {
							throw new Exception("过期的备忘录！");
						} catch (Exception e) {
							e.printStackTrace();
						}
                    }else {
                        map.put("startTime","(距离会议开始还有"+days+"天)");
                    }
				}
			}
		}
	}
}
